import { AddOutline } from 'antd-mobile-icons'
import { Form, Input, Selector, Button, DatePicker, Ellipsis, Stepper, Picker, type PickerRef } from 'antd-mobile'
import { useEffect, useState, type RefObject } from 'react'
import dayjs from 'dayjs'
import mapdataApi from '../Api/mapData'
import { useNavigate } from 'react-router-dom'
import CustomItem from './customer/CustomItem'
import { setUserInfo, setStep } from '../store/UserSlice'
import { useDispatch, useSelector } from 'react-redux'
import { MailOpenOutline } from 'antd-mobile-icons'
import type { ICustomerItem } from '../interface/IlistItem'
import './FormInfo.scss'

function FormInfo() {
  const step = useSelector((state: any) => state.user.step)
  const navigate = useNavigate()
  const dispatch = useDispatch()
  const { newReceiptionItem } = useSelector((state: any) => state.user)
  const newData = {
    ...newReceiptionItem,
    dateFrom: newReceiptionItem === 0 ? new Date(0) : new Date(newReceiptionItem.dateFrom),
    dateTo: newReceiptionItem === 0 ? new Date(0) : new Date(newReceiptionItem.dateTo),
  }
  const [form] = Form.useForm()
  useEffect(() => {
    mapdataApi().then((res) => {
      setColumns(res.receptionCategory)
    })
    form.setFieldsValue(newData)
  }, [])
  let customer = newData.LikeAndDislike
  const [visible1, setVisible1] = useState(false)
  const [visible2, setVisible2] = useState(false)
  const [columns, setColumns] = useState([])
  const options = [
    {
      label: '常州',
      value: 1,
    },
    {
      label: '上海',
      value: 2,
    },
    {
      label: '德阳',
      value: 3,
    },
    {
      label: '北京',
      value: 4,
    },
    {
      label: '重庆',
      value: 5,
    },
  ]
  function SubmitHandle(e: any) {
    e.preventDefault()
    form.validateFields().then(values => {
      const data = {
        ...values,
        dateFrom: form.getFieldValue('dateFrom').getTime(),
        dateTo: form.getFieldValue('dateTo').getTime(),
      }
      dispatch(setUserInfo(data))
      dispatch(setStep(step + 1))
      navigate('/home/step2')
    }).catch(err => {
      console.log('验证失败:', err);
    });
  }
  return (
    <>
      <main>
        <div className='FormInfo'>
          <Form
            form={form}
            initialValues={newData}
            layout='horizontal'
            key={form.getFieldValue('billNo')}
          >
            <Form.Header>
              <p className='titleStyle'>基本信息</p>
            </Form.Header>
            <Form.Item
              name='itemMaker'
              label='制单人'
              rules={[{ required: true, message: '制单人不能为空' }]}
            >
              <Input placeholder='请输入制单人' />
            </Form.Item>
            <Form.Item
              name='applier'
              label='申请人'
              rules={[{ required: true, message: '申请人不能为空' }]}
            >
              <Input placeholder='请输入申请人' />
            </Form.Item>
            <Form.Item
              name='taskBody'
              label='业务主体'
              rules={[{ required: true, message: '业务主体不能为空' }]}
            >
              <Input placeholder='请输入业务主体' />
            </Form.Item>
            <Form.Item
              name='costCenter'
              label='成本中心'
              rules={[{ required: true, message: '成本中心不能为空' }]}
            >
              <Input placeholder='请输入成本中心' />
            </Form.Item>
            <Form.Item
              name='billNo'
              label='预算号'
              rules={[{ required: true, message: '预算号不能为空' }]}
            >
              <Input placeholder='请输入预算号' />
            </Form.Item>
            <Form.Header>
              <p className='titleStyle'>接待信息</p>
            </Form.Header>
            <Form.Item
              name='location'
              label='接待地点'
              rules={[{ required: true, message: '接待地点不能为空' }]}
            >
              <Selector
                options={options}
                multiple
              />
            </Form.Item>
            <Form.Item
              label='接待开始时间'
              trigger='onConfirm'
              name='dateFrom'
              rules={[{ required: true, message: '接待开始时间不能为空' }]}
              onClick={() => {
                setVisible1(true)
              }}
            >
              <DatePicker
                tillNow={true}
                mouseWheel={true}
                visible={visible1}
                onClose={() => {
                  setVisible1(false)
                }}
                onConfirm={(val) => {
                  console.log(val)
                }}
                precision='hour'
              >
                {value =>
                  <div style={{ color: '#000000ff' }}>{value ? (value.getTime() === 0 ? <span style={{ color: 'grey' }}>请选择接待开始时间</span> : dayjs(value).format('YYYY-MM-DD hh:mm:ss')) : ''}</div>
                }
              </DatePicker>
            </Form.Item>
            <Form.Item
              name='dateTo'
              label='接待结束时间'
              trigger='onConfirm'
              onClick={() => {
                setVisible2(true)
              }}
            >
              <DatePicker
                min={new Date(form.getFieldValue('dateFrom'))}
                max={new Date((form.getFieldValue('dateFrom'))?.getTime() + 48 * 3600000)}
                mouseWheel={true}
                visible={visible2}
                onClose={() => {
                  setVisible2(false)
                }}
                onConfirm={(val) => {
                  console.log(val)
                }}
                precision='hour'
              >
                {value =>
                  <div style={{ color: '#000000ff' }}>{value ? (value.getTime() === 0 ? <span style={{ color: 'grey' }}>请选择接待开始时间</span> : dayjs(value).format('YYYY-MM-DD hh:mm:ss')) : ''}</div>
                }
              </DatePicker>
            </Form.Item>
            {columns && <Form.Item name='type' label='接待类别'
              required
              trigger='onConfirm'
              rules={[{ required: true, message: '接待类别不能为空' }]}
              onClick={(_, pickerRef: RefObject<PickerRef>) => {
                pickerRef.current?.open()
              }}
            >
              <Picker title='接待类别' columns={[columns]}>{
                (value) => value.every(item => item === null)
                  ? <div>未选择</div>
                  : <Ellipsis direction='end' rows={2} content={value.map(item => item?.label ?? '未选择').join(' - ')} />
              }</Picker>
            </Form.Item>}
            <Form.Item
              name='companyName'
              label='来访单位'
              rules={[{ required: true, message: '来访单位不能为空' }]}
            >
              <Input placeholder='请输入来访单位' />
            </Form.Item>
            <Form.Item
              name='visitNum'
              label='来访认数'
              rules={[{ required: true, message: '来访认数不能为空' }]}
            >
              <Stepper min={1} max={20} />
            </Form.Item>
            <Form.Item
              name='visitPurpose'
              label='来访目的'
              rules={[{ required: true, message: '来访目的不能为空' }]}
            >
              <Input placeholder='请输入来访目的' />
            </Form.Item>
            <Form.Item
              name='LikeAndDislike'
              label='重要客户喜好&禁忌'
              rules={[{ required: true, message: '客户喜好与禁忌不能为空' }]}
            >
              <div className='LikeAndDislike' onClick={() => {
                const data = {
                  ...form.getFieldsValue(),
                  dateFrom: form.getFieldValue('dateFrom').getTime(),
                  dateTo: form.getFieldValue('dateTo').getTime(),
                }
                dispatch(setUserInfo(data))
                console.log(data)
                navigate("/add/detail")
              }}>
                <span style={{ color: "#000", marginRight: "10px" }}>{newData.LikeAndDislike.length === 0 ? "" : "已添加" + newData.LikeAndDislike.length + "人"}</span>
                <AddOutline onClick={() => {
                }} color='var(--adm-color-primary)' />添加
              </div>
            </Form.Item>
            {customer.map((item: ICustomerItem) => <CustomItem itemData={item} key={item.id} />)}
            <Form.Item
              name='accompany'
              label='陪同人员'
              rules={[{ required: true, message: '陪同人员不能为空' }]}
            >
              <Input placeholder='请输入陪同人员' />
            </Form.Item>
            <Form.Item
              name='vehicles'
              label='来访车辆'
              rules={[{ message: '来访车辆不能为空' }]}
            >
              <div style={{ color: '#1677FF' }}>
                <AddOutline color='var(--adm-color-primary)' />添加
              </div>
            </Form.Item>
          </Form>
        </div >
      </main>
      <footer>
        <div className='stepBtn'>
          <div>
            <MailOpenOutline />
            <span>存草稿</span>
          </div>
          <Button onClick={
            SubmitHandle
          } color='primary' size='large'>
            下一步
          </Button>
        </div>
      </footer>
    </>
  )
}
export default FormInfo